package org.jwt.oauth.config;

import java.util.Map;

import org.jwt.oauth.tools.FusionJwtTools;
import org.jwt.oauth.user.FusionUserDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

@Component
public class JwtTokenEnhancer implements TokenEnhancer {

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
		String refreshToken = oAuth2AccessToken.getRefreshToken().getValue();
		// 当为刷新token的时候
		if (refreshToken != null && refreshToken.length() > 100) {
			Map<String, Object> loginUserInfo = FusionJwtTools.getLoginUserInfo(refreshToken);
			((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(loginUserInfo);
		} else {
			Object principal = oAuth2Authentication.getPrincipal();
			FusionUserDetails userData = (FusionUserDetails) principal;
			Map<String, Object> dataMap = userData.getDataMap();
			((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(dataMap);
		}
		return oAuth2AccessToken;
	}
}